package cn.com.callback
import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

/**
 *
 * @Title: main.java.cn.com.callback-autoSendMessage
 * @Description:ngsapitask-pa 处理短信新增多线程表
 * @Author: TaoHao
 * @Date 2025/7/11 16:00
 *
 */

public class autoSendMessage implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoSendMessage.class);

    @Override
    void doCallBack(EliteBean eliteBean, String s, Map map, String s1) {
        log.warn("---autoSendMessage---");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //关闭开启锁SQL
        String updatesql = '''update sysc_parameter set PARAMETERVALUE=? where PARAMETER_ID='SMLOCK' ''';
        try {

            //悲观数据锁-防止重复新增数据
            if (KHDBConfig.getParam(eliteBean, "SMLOCK") == "OPEN") {
                //将锁开启
                jt.update(updatesql,'CLOSE');
                String InsertSelectSql='''
                   Insert into elitethread(thread_guid,type,status,content,createdate)
                   select uuid(),'auto_SMS_Thread',0,d.Documentout_Guid,Now()
                   From Documentout d
                   LEFT JOIN elitethread e on e.content=d.Documentout_Guid
                   Where d.Doctype In (3, 4, 5)
                   And d.Status = 0
                   and  e.content is null 
                   And d.Trialcount < d.Trialcountlimit
                   And Ifnull(d.Expectedstartdate, Now()) <= Now()
                      ''';
                int InsertNum=jt.update(InsertSelectSql);
                log.debug("【autoSendMessage】本次新增到线程表数量:" +InsertNum);

                //状态=3的数据在线程表重新删除
                String DelSql='''DELETE FROM elitethread WHERE status='3' and type='auto_SMS_Thread'  ''';
                int DelNum=jt.update(DelSql);
                log.debug("【autoSendMessage】本次删除线程表数量:" +DelNum);

                //将锁关闭
                jt.update(updatesql,'OPEN');
            }

        }catch (Exception e) {
            log.error("【autoSendMessage】本次新增到线程表异常!", e);
            //将锁关闭
            jt.update(updatesql,'OPEN');
        }


    }
}
